//
//  RelatedAlbumViewController.m
//  Atlantis
//
//  Created by 何恩营 on 14-12-26.
//  Copyright (c) 2014年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "RelatedAlbumViewController.h"
#import "NetHandler.h"
#import "AlbumCell.h"
#import "Album.h"
#import "AlbumDetailsViewController.h"

#import "UIScrollView+Extension.h"
#import "UIScrollView+MJRefresh.h"

#define REUSE @"reuse"

@interface RelatedAlbumViewController ()<UITableViewDataSource, UITableViewDelegate>

// 页码
@property(nonatomic, assign) NSInteger page;
// 表视图
@property(nonatomic, retain) UITableView *tableView;

// 专辑数组
@property (nonatomic, retain) NSMutableArray *albumArr;

@end

@implementation RelatedAlbumViewController

// 内存管理
- (void)dealloc
{
    // Album对象
    [_album release];
    // 表视图
    [_tableView release];
    // 专辑数组
    [_albumArr release];
    [super dealloc];
}

- (void)setupRefresh
{
    //    NSLog(@"进入了setupRefresh");
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    
    [self.tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    //进入刷新状态(一进入程序就下拉刷新)
    [self.tableView headerBeginRefreshing];
    
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [self.tableView addFooterWithTarget:self action:@selector(footerRereshing)];
}
#pragma mark 开始进入刷新状态
- (void)headerRereshing
{
    UIView *view = [[UIView alloc] initWithFrame:self.view.bounds];
    view.backgroundColor = [UIColor clearColor];
    [self.view addSubview:view];
    [view release];
    
    //1. 在这调用请求网络数据方法（刷新数据）
    self.page = 1;
    [self handleData];
    //2. 2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        //[self.tableView reloadData];
        [view removeFromSuperview];
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.tableView headerEndRefreshing];
    });
}

//   进入加载状态
- (void)footerRereshing
{
    self.page += 1;
    //1. 拼接口等操作
    // 请求加载数据
    [self footerHandleData];
    
    // 2.2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.tableView reloadData];
        [self.tableView footerEndRefreshing];
    });
}

// 处理数据
- (void)handleData
{
    // 创建连接
    NSString *path = [NSString stringWithFormat: @"http://mobile.ximalaya.com/mobile/others/ca/album/%@/%ld/30?device=iPhone", self.album.uid, self.page] ;
    
    // 建立连接
    [NetHandler getDataWithURL:path completion:^(NSData *data) {
        
        id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        // 获取数组
        NSArray *listArr = [result objectForKey:@"list"];
        // 初始化
        self.albumArr = [NSMutableArray array];
        // 遍历数组
        for (NSDictionary *dic in listArr) {
            // 创建对象
            Album *album = [[Album alloc] initWithDictionary:dic];
            // 赋值
            [self.albumArr addObject:album];
            // 内存管理
            [album release];
        }
        // 刷新视图
        [self.tableView reloadData];
        [self setupRefresh];
    }];
}

// 处理页脚数据
- (void)footerHandleData
{
    // 创建连接
    NSString *path = [NSString stringWithFormat: @"http://mobile.ximalaya.com/mobile/others/ca/album/%@/%ld/30?device=iPhone", self.album.uid, self.page] ;
    // 建立连接
    [NetHandler getDataWithURL:path completion:^(NSData *data) {
        id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        // 获取数组
        NSArray *listArr = [result objectForKey:@"list"];
        // 遍历数组
        for (NSDictionary *dic in listArr) {
            // 初始化对象
            Album *album = [[Album alloc] initWithDictionary:dic];
            // 赋值
            [self.albumArr addObject:album];
            // 内存管理
            [album release];
        }
    }];
    
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    // 视图背景颜色
    self.view.backgroundColor = [UIColor whiteColor];
    
    // 导航栏标题
    self.navigationItem.title = [NSString stringWithFormat:@"%@ 相关专辑", self.album.nickname];
    
    // 页数
    self.page = 1;
    // 调用处理数据
    [self handleData];
    
    // 创建表视图
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain] ;
    // 指定代理人
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    // 视图加载
    [self.view addSubview:self.tableView];
    // 内存管理
    [_tableView release];
    
    // 注册cell
    [self.tableView registerClass:[AlbumCell class] forCellReuseIdentifier:REUSE];
    
    
    // 导航栏左侧返回按钮
    self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"return.png"] style:UIBarButtonItemStyleDone target:self action:@selector(collectionAction:)] autorelease];
    
}


// 导航栏左侧返回按钮触发事件
- (void)collectionAction:(UINavigationBar *)bar
{
    //NSLog(@"返回前一页");
    // 推出前一页
    [self.navigationController popViewControllerAnimated:YES];
}

// cell的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 150;
}

// cell的行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.albumArr.count;
}

// cell的值
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 自定义cell
    AlbumCell *cell = [tableView dequeueReusableCellWithIdentifier:REUSE];
    // 赋值
    cell.alb = [self.albumArr objectAtIndex:indexPath.row];
    return cell;
}

// 点击cell实现方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    // 创建视图
    AlbumDetailsViewController *albumDetail = [[AlbumDetailsViewController alloc] init];
    // 赋值
    albumDetail.album = [self.albumArr objectAtIndex:indexPath.row];
    // 推出界面
    [self.navigationController pushViewController:albumDetail animated:YES];
    // 内存管理
    [albumDetail release];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
